package com.example.jianbing.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName : ThreadWaitNotifyNewVersionDemo
 * @Description :
 * @Author : JB
 * @Date: 2020-08-04 01:50
 */

class AirConditioner1{
    private int  number = 0;
    public Lock lock = new ReentrantLock();
    public Condition condition = lock.newCondition();
    //加1
    public  void  increment() throws InterruptedException {
        lock.lock();
        try {
            //1.判断
            while(number != 0){
                //要用while做判断
               condition.await(); //this.wait();
            }
            //2. 干活
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //3. 通知
            condition.signalAll();  //this.notifyAll();
        }finally {
            lock.unlock();
        }

    }
    //减1
    public   void decrement() throws InterruptedException {

        lock.lock();
        try {
            //1.判断
            while(number == 0){
                condition.await(); //this.wait();
            }
            //2. 干活
            number--;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //3. 通知
            condition.signalAll();  //this.notifyAll();
        }finally {
            lock.unlock();
        }


    }
}

/***
 * 题目： 现在两个线程，可以操作初始值为零的一个变量
 *  实现一个线程对该变量的加1，一个线程对该变量的减1
 *  实现交替，来10轮，变量初始值变成0
 *
 * 步骤：
 *       1.高内聚低耦合下，线程操作资源类
 *       2. 判断/干活/通知
 *       3. 多线程交互中，必须要防止多线程的虚假唤醒，不能用if做判断,用while(循环监听)
 */
public class ThreadWaitNotifyNewVersionDemo {
    public static void main(String[] args) {
        AirConditioner1 airConditioner = new AirConditioner1();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airConditioner.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airConditioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}
